﻿
using System;

using TVA;
using TVA.PhasorProtocols.IeeeC37_118;

namespace GridStatLite
{
    static class Utility
    {
        private const uint TimeBase = 16777215U;

        public static int ToBinary(this Ticks ticks, byte[] buffer, int offset)
        {
            UnixTimeTag tmtag = new UnixTimeTag(ticks);

            uint secondOfCentury = (uint)Math.Truncate(tmtag.Value);
            UInt24 fractionOfSecond = (UInt24)((decimal)ticks.DistanceBeyondSecond() / (decimal)Ticks.PerSecond * (decimal)TimeBase);

            int position = offset;
            EndianOrder.BigEndian.CopyBytes(secondOfCentury, buffer, position);
            position += 4;

            EndianOrder.BigEndian.CopyBytes((uint)(fractionOfSecond | (int)TimeQualityFlags.NoFlags), buffer, position);
            position += 4;

            return position - offset;
        }

        public static Tuple<Ticks, int> ToTicks(this byte[] buffer, int offset)
        {
            int position = offset;
            uint secondOfCentury = EndianOrder.BigEndian.ToUInt32(buffer, position);
            position += 4;

            uint fractionOfSecond = EndianOrder.BigEndian.ToUInt32(buffer, position);
            position += 4;

            Ticks timestamp = (new UnixTimeTag((double)secondOfCentury)).ToDateTime().Ticks;
            decimal fractionalSeconds = (fractionOfSecond & ~TVA.PhasorProtocols.IeeeC37_118.Common.TimeQualityFlagsMask) / (decimal)TimeBase;
            timestamp += (long)(fractionalSeconds * (decimal)Ticks.PerSecond);

            return Tuple.Create(timestamp, position - offset);
        }
    }
}
